<template>
  <div>
    <el-card style="margin: 20px 0px">
      <CategorySelect @getCategoryId="getCategoryId" :show="isShowTable"/>
    </el-card>
    <el-card>
      <!--属性展示-->
      <div v-show="isShowTable">
        <el-button type="primary" icon="el-icon-plus" :disabled="!category3Id" @click="addAttr">添加属性</el-button>
        <el-table :data="attrList" style="width: 100%" border>
          <el-table-column type="index" label="序号" align="center" width="80"></el-table-column>
          <el-table-column prop="attrName" label="属性名称" width="150"></el-table-column>
          <el-table-column label="属性值列表" width="width">
            <template slot-scope="{row,$index}">
              <el-tag type="success" v-for="attrValue in row.attrValueList" :key="attrValue.id"
                      style="margin: 0px 12px">{{ attrValue.valueName }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template slot-scope="{row}">
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="updateAttract(row)"></el-button>
              <el-popconfirm :title="`确定删除${row.valueName}吗？`" @onConfirm="deleteAttr(row.id)">
                <el-button type="warning" slot="reference" icon="el-icon-delete" size="mini"></el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!--添加或修改属性-->
      <div v-show="!isShowTable">
        <el-form :inline="true" ref="form" class="demo-form-inline" :model="attrInfo">
          <el-form-item label="属性名">
            <el-input placeholder="请输入属性名" v-model="attrInfo.attrName"></el-input>
          </el-form-item>
        </el-form>
        <el-button type="primary" icon="el-icon-plus" :disabled="!attrInfo.attrName" @click="addAttrValue">添加属性值
        </el-button>
        <el-table :data="attrInfo.attrValueList" style="width: 100%;margin: 20px 0px" border>
          <el-table-column type="index" label="序号" align="center" width="80"></el-table-column>
          <el-table-column label="属性值名称" width="width">
            <template slot-scope="{row,$index}">
              <div>
                <!--来回切换-->
                <el-input v-model="row.valueName" :ref="$index" placeholder="请输入属性值名称" size="mini" v-if="row.flag" @blur="toLook(row)" @keyup.enter.native="toLook(row)"></el-input>
                <span v-else @click="toEdit(row,$index)" style="display: block">{{row.valueName}}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="date" label="操作" width="width">
            <!--气泡确认框-->
            <template slot-scope="{row,$index}">
              <el-popconfirm :title="`确定删除${row.valueName}吗？`" @onConfirm="deleteAttrValue($index)">
                <el-button slot="reference" type="danger" icon="el-icon-delete" size="mini" ></el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" :disabled="attrInfo.attrValueList.length<1" @click="addOrUpdateAttr">保存</el-button>
        <el-button @click="isShowTable=true">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
//引入lodash的深拷贝
import cloneDeep from 'lodash/cloneDeep'
export default {
  name: 'attr',
  data() {
    return {
      category1Id: '',
      category2Id: '',
      category3Id: '',
      isShowTable: true,//是否展示第二个卡片
      attrList: [],//接收服务器返回的平台属性数据
      //收集新增或修改的属性名
      attrInfo: {
        attrName: '',//属性名
        attrValueList: [],//属性值 可以有多个
        categoryId: 0,//三级分类ID
        categoryLevel: 3//区分几级id
      }
    }
  },
  methods: {
    //自定义事件回调 获取分类id
    getCategoryId(cForm) {
      this.category1Id = cForm.category1Id
      this.category2Id = cForm.category2Id
      this.category3Id = cForm.category3Id
      if (this.category3Id) {
        this.getAttrList()
      }
    },
    //获取平台属性
    async getAttrList() {
      try {
        const { category1Id, category2Id, category3Id } = this
        let res = await this.$API.attr.reqGetAttr(category1Id, category2Id, category3Id)
        if (res.code === 200) {
          this.attrList = res.data
        }
      } catch (e) {
        alert(e.message)
      }
    },
    //添加属性值按钮
    addAttrValue() {
      //向属性值的数组里面添加数据
      this.attrInfo.attrValueList.push({
        attrId: this.attrInfo.id, //相应属性名的id
        valueName: '' ,//属性值名称
        //input和span切换
        flag:true,
      })
      //聚焦 有可能组件没出来就聚焦了,所以需要nextTick
      this.$nextTick(()=>{
        this.$refs[this.attrInfo.attrValueList.length-1].focus()
      })
    },
    //添加属性按钮
    addAttr(){
      this.isShowTable = false
      //清除数据 并设置三级分类id
      this.attrInfo = {
        attrName: '',//属性名
        attrValueList: [],//属性值 可以有多个
        categoryId: this.category3Id,//三级分类ID
        categoryLevel: 3//区分几级id
      }

    },
    //修改属性
    updateAttract(attrInfo){
      this.isShowTable = false
      //将选中的信息赋给变量
      //由于数据结构复杂 需要属于深拷贝解决问题(修改数据但点击取消返回后仍显示修改的数据:双向绑定)
      //this.attrInfo = {...attrInfo} 不能解决问题
      this.attrInfo = cloneDeep(attrInfo)
      // 将flag加上数组
      this.attrInfo.attrValueList.forEach((item)=>{
        //不能这样写:item.flag = false 不是响应式数据 不能实现页面实时更新
        this.$set(item,'flag',false)
      })
    },
    //切换查看模式 失去焦点时
    toLook(row){
      //row是当前用户添加的最新的属性值
      //不能为空
      if (row.valueName.trim() === ''){
        this.$message('请输入正常的属性值')
        return
      }
      //属性值不能重复
      let isRepeat = this.attrInfo.attrValueList.some((item)=>{
        //不比较row本身 row是attrValueList中的一项 即最新增加的那一项
        if (row!==item){
          return row.valueName === item.valueName
        }
      })
      if (isRepeat){
        this.$message('属性值不能重复')
        this.attrInfo.attrValueList.pop()
        return;
      }
      //显示span
      row.flag = false
    },
    //切换编辑模式 失去焦点时
    toEdit(row,index){
      row.flag = true
      //自动获取焦点 保证input被渲染出来再聚焦
      this.$nextTick(()=>{
        console.log(this.$refs)
        this.$refs[index].focus()
      })
    },
    //删除属性值 气泡确认框的确认回调 新版本中的气泡回调是 confirm 现在使用的是旧版 onConfirm
    deleteAttrValue(index){
      this.attrInfo.attrValueList.splice(index,1)
    },
    //保存按钮
    async addOrUpdateAttr(){
      // 整理参数
      //1.空属性值不需要 2.flag字段不需要
      this.attrInfo.attrValueList = this.attrInfo.attrValueList.filter((item)=>{
        if (item.valueName!==''){
          delete item.flag
          return true
        }
      })
      try {
        let res = await this.$API.attr.reqAddOrUpdateAttr(this.attrInfo)
        if (res.code === 200){
          this.$message({type:'success',message:'保存成功'})
          await this.getAttrList()
          this.isShowTable = true
        }
      }catch (e) {
        alert(e.message)
      }
    },
    //删除属性
    async deleteAttr(id){
      try {
        let res = await this.$API.attr.reqDeleteAttr(id)
        if (res.code === 200){
          this.$message({
              type:'success',
              message:'删除成功'
          })
          this.getAttrList()
        }
      }catch (e) {

      }
    }
  },
}
</script>

<style scoped>

</style>
